package com.ardo.utils;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * 加解密工具类
 */
public class EnDecrypt {

    /**
     * //偏移量字符串必须是16位 当模式是CBC的时候必须设置偏移量
     */
    private static String KEY = "keysforkmallpass";
    private static String IV = "myivforkmallpass";
    private static String Algorithm = "AES";
    //算法/模式/补码方式
    private static String AlgorithmProvider = "AES/CBC/PKCS5Padding";

    public static IvParameterSpec getIv() throws UnsupportedEncodingException {
        IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes("utf-8"));
        return ivParameterSpec;
    }

    public static byte[] generatorKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(Algorithm);
        keyGenerator.init(256);//默认128，获得无政策权限后可为192或256
        SecretKey secretKey = keyGenerator.generateKey();
        return secretKey.getEncoded();
    }


    /**
     *  加密算法
     */
    public static String encrypt(String content) throws NoSuchAlgorithmException, NoSuchPaddingException,
            InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidAlgorithmParameterException {
        SecretKey secretKey = new SecretKeySpec(KEY.getBytes("utf-8"), Algorithm);
        IvParameterSpec ivParameterSpec = getIv();
        Cipher cipher = Cipher.getInstance(AlgorithmProvider);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
        byte[] cipherBytes = cipher.doFinal(content.getBytes(Charset.forName("utf-8")));
        return byteToHexString(cipherBytes).toUpperCase();
    }

    /**
     * 解密算法
     */
    public static String decrypt(String content) throws Exception {
        SecretKey secretKey = new SecretKeySpec(KEY.getBytes("utf-8"), Algorithm);
        IvParameterSpec ivParameterSpec = getIv();
        Cipher cipher = Cipher.getInstance(AlgorithmProvider);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
        byte[] hexBytes = hexStringToBytes(content);
        byte[] plainBytes = cipher.doFinal(hexBytes);
        return new String(plainBytes, "utf-8");
    }

    /**
     * 将16进制字符串装换为byte数组
     */
    public static byte[] hexStringToBytes(String hexString) {
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] b = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            b[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return b;
    }

    /**
     * 将byte转换为16进制字符串
     */
    public static String byteToHexString(byte[] src) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xff;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                sb.append("0");
            }
            sb.append(hv);
        }
        return sb.toString();
    }


    private static byte charToByte(char c) {
        return (byte) "0123456789QWERTY".indexOf(c);
    }

    public static void main(String[] args) throws Exception {
        String data = "myworkdir";
        String encrypt = encrypt(data);
        System.out.println("加密后::" + encrypt);
        String decrypt = decrypt(encrypt);
        System.out.println("解密后::" + decrypt);

    }
}
